/**
 * 广告弹层，移动端
 */
(function () {
    function setCookie(name, value, expires) {
        var Days = expires || 7;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
    }

    //读取cookies
    function getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

        if (arr = document.cookie.match(reg)) {
            return unescape(arr[2]);
        } else {
            return null;
        }
    }

    var now = function () {
        if (typeof window.GET_SERVER_TIME === 'function') {
            return window.GET_SERVER_TIME();
        } else {
            return new Date();
        }
    };

    /**
     * 展示弹层
     * @param {string} html
     * @param {{close?:Function,show?:Function,timeout?:number}?} opt
     */
    function showPopup(html, opt) {
        var onClose = opt.close;
        var onShow = opt.show;
        var timeout = opt.timeout;
        var autoCloseTimer;

        if (typeof timeout !== 'undefined') {
            autoCloseTimer = setTimeout(function () {
                close();
            }, timeout);
        }

        var maskDiv = '<div style="position: fixed;top: 0;bottom: 0;width: 100%;z-index: 10000;opacity: 0.7;background: #000;"></div>';
        var happyDiv = '<div style="position: fixed;z-index: 10001;top: 0;bottom: 0;width: 100%;height: 100%;">' + html + '</div>';
        var div = document.createElement('div');
        div.innerHTML = maskDiv + happyDiv;

        div.onclick = function () {
            close();
        };

        if (window.attachEvent) {
            window.attachEvent('onload', show);
        } else {
            window.addEventListener('load', show);
        }

        function close() {
            autoCloseTimer && clearTimeout(autoCloseTimer);

            document.querySelector('body').removeChild(div);

            if (typeof onClose === 'function') {
                onClose();
            }
        }

        function show() {
            document.querySelector('body').appendChild(div);

            if (typeof onShow === 'function') {
                onShow();
            }
        }
    }

    /**
     * 资源加载
     * @param {Array.<string>} urls
     * @param {function(Array.<{url:string,loaded:boolean,complete:boolean}>)} callback 加载完成回调
     * @constructor
     */
    var ResourceLoader = function (urls, callback) {
        var configs = [];
        for (var i = 0; url = urls[i]; i++) {
            configs.push({url: url, loaded: false, complete: false});
        }

        function onFinish(i, loaded) {
            return function () {
                var configItem = configs[i];
                configItem.loaded = loaded;
                configItem.complete = true;

                if (typeof callback === 'function') {
                    var flag = true;

                    var config;
                    for (var j = 0; config = configs[j]; j++) {
                        if (!config.complete) {
                            flag = false;
                            break;
                        }
                    }

                    if (flag) {
                        callback(configs);
                    }
                }
            }
        }

        var url;
        for (var i = 0; url = urls[i]; i++) {
            var img = new Image();

            img.onload = onFinish(i, true);
            img.onerror = onFinish(i, false);

            img.src = url;
        }
    };

    /**
     * @param {{
     * key:string,
     * html:string,
     * showPop?:boolean,
     * showCallback?:Function,
     * expires?:number,
     * startTime?:number,
     * endTime?:number,
     * timeout?:number,
     * close?:Function,
     * show?:Function,
     * preLoadImages?:Array.<string>
     * }} opt
     */
    window.POP_1AD1_Mobile = function (opt) {
        var key = opt.key;
        var html = opt.html;
        var expires = opt.expires;
        var startTime = opt.startTime;
        var endTime = opt.endTime;
        var showPop = opt.showPop;
        var showCallback = opt.showCallback;
        var preLoadImages = opt.preLoadImages;

        if (typeof showPop === 'undefined') {
            showPop = true;
        }

        var show = false;
        var setShow = true;
        if (typeof expires !== 'undefined') {
            show = setShow = getCookie(key) != '1';
        }

        if (typeof startTime !== 'undefined') {
            show = setShow = setShow && now().getTime() >= startTime;
        }

        if (typeof endTime !== 'undefined') {
            show = setShow = setShow && now().getTime() < endTime;
        }

        if (show) {
            if (typeof showCallback === 'function') {
                showCallback();
            }

            if (showPop) {
                var run = function () {
                    showPopup(html,
                        {
                            close: function (pop) {
                                var onClose = opt.close;
                                if (typeof onClose === 'function') {
                                    onClose(pop);
                                }

                                if (typeof expires !== 'undefined') {
                                    setCookie(key, '1', expires);
                                }
                            },
                            timeout: opt.timeout,
                            show: opt.show
                        }
                    );
                };

                if (preLoadImages) {
                    new ResourceLoader(preLoadImages, run);
                } else {
                    run();
                }
            }
        }
    }
}());
